package com.alog.senior.day22;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/1/25 14:37
 * @Description:
 */
public class ServerTest {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8087);
        while(true){
            Socket socket = ss.accept();
            new Thread(() -> {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    //System.out.println(br.readLine());
                    String request = br.readLine();
                    String[] splits = request.split(" ");
                    String path = "";
                    if(splits[1].length() == 1){
                        path = "E:\\videos\\java2018\\Java基础第二部分课程资料\\day11\\上课资源文件\\web\\index.html";
                    } else {
                        path = "E:\\videos\\java2018\\Java基础第二部分课程资料\\day11\\上课资源文件\\web\\" + splits[1].substring(1);
                    }

                    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

                    bos.write("HTTP/1.1 200 OK\r\n".getBytes());
                    bos.write("Content-Type:text/html\r\n".getBytes());
                    bos.write("\r\n".getBytes());

                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while((len = bis.read(buf)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bos.flush();
                    bis.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
